package cn.bitkit.component.common;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import cn.bitkit.base.exception.BusinessException;

/**
 * 数据验证器
 * @author changbo
 *
 */
public class ValidateHandler {
	
	private static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();
	
	public static void checkAssert(Object obj, Class<?>... groups) {
		List<String> result = check(obj, groups);
		if(result == null || result.isEmpty()) {
			return;
		}
		throw new BusinessException(String.join("; ", result));
	}
	
	public static List<String> check(Object obj, Class<?>... groups) {
		if(obj == null){
			return Collections.emptyList();
		}
		Validator validator = FACTORY.getValidator();
		Set<ConstraintViolation<Object>> set = validator.validate(obj, groups);
		if(set == null || set.isEmpty()) {
			return Collections.emptyList();
		}
		return set.stream().map(ConstraintViolation::getMessage)
				.collect(Collectors.toList());
	}

}
